//
//  UIPageScrollView.m
//  FingerChinese
//
//  Created by luar on 14/02/2010.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "UIPageScrollView.h"
#import "PageView.h"

@implementation UIPageScrollView

@synthesize frameWidth, canDoubleTapZoom, frameHeight, pageQuantity, pageNo, isHorizontalScroll, host;

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code
		isHorizontalScroll = YES;
		canDoubleTapZoom = YES;
		pageGap = 50;
		pageNo = 0;
		self.maximumZoomScale = 1;
		self.decelerationRate = 0;
		self.showsHorizontalScrollIndicator = NO;
		self.showsVerticalScrollIndicator = NO;
		//self.directionalLockEnabled = YES;
		self.alwaysBounceVertical = YES;
		self.alwaysBounceHorizontal = YES;
		self.delegate = self;
		self.backgroundColor = [UIColor clearColor];
    }
	//NSLog(@"UIPageScrollView initWithFrame");
    return self;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	[self updateInterfaceOrientation];
	return YES;
}

- (void)updateInterfaceOrientation {
	if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft || [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight) {
		self.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
		self.minimumZoomScale = [UIScreen mainScreen].bounds.size.height/pageOriginalWidth+0.001;
	} else {
		self.frame = [UIScreen mainScreen].bounds;
		self.minimumZoomScale = [UIScreen mainScreen].bounds.size.width/pageOriginalWidth+0.001;
	}
	if (!canDoubleTapZoom) {
		self.minimumZoomScale = 1;
	}
	pageWidth = pageOriginalWidth*self.minimumZoomScale;
	pageHeight = pageOriginalHeight*self.minimumZoomScale;
	pageWidth2 = pageWidth / 2;
	pageHeight2 = pageHeight / 2;
	curPage = pageL;
	[self setZoomScale:self.minimumZoomScale];
	curPage = pageR;
	[self setZoomScale:self.minimumZoomScale];
	curPage = page;
	[self setZoomScale:self.minimumZoomScale];
	if (isHorizontalScroll) {
		pageL.center = CGPointMake(page.center.x-pageWidth-pageGap, pageHeight2);
		pageR.center = CGPointMake(page.center.x+pageWidth+pageGap, pageHeight2);		
	} else {
		pageL.center = CGPointMake(pageWidth2, page.center.y-pageHeight-pageGap);
		pageR.center = CGPointMake(pageWidth2, page.center.y+pageHeight+pageGap);
	}
	[self setContentOffset:CGPointMake(0, 0)];
	NSLog(@"UIPageScrollView shouldAutorotateToInterfaceOrientation minimumZoomScale:%f, page.center.x:%f, contentSize:%f %f, isHorizontalScroll:%i, pageQuantity:%i, pageOriginal:%i %i", self.minimumZoomScale, page.center.x, self.contentSize.width, self.contentSize.height, isHorizontalScroll, pageQuantity, pageOriginalWidth, pageOriginalHeight);
}

#pragma mark -
#pragma mark Page Related

- (void)initPage {
	[self getPage:pageNo isNewPage:TRUE];
	pageOriginalWidth = page.frame.size.width;
	pageOriginalHeight = page.frame.size.height;
	
	[self addSubview:pageL];
	[self addSubview:page];
	[self addSubview:pageR];
	[self updateInterfaceOrientation];
	//NSLog(@"UIPageScrollView initPage %@ %i %i", self.superview, pageOriginalWidth, pageOriginalHeight);
	
	if (canDoubleTapZoom) {
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doubleTapZoom:) name:@"DoubleTapZoom" object:nil];
	}	
}

- (void)getPage:(NSInteger)pageIndex isNewPage:(BOOL)newPage {
	if (newPage) {
		pageL = [host genPage:0 isNewPage:newPage];
		[self removeAll:pageL];
	} else {
		if (pageIndex>0) {
			curPage = pageL;
			pageL = [host genPage:pageIndex-1 isNewPage:newPage];
		} else {
			[self removeAll:pageL];
		}		
	}
	if (pageIndex<pageQuantity-1) {
		curPage = pageR;
		pageR = [host genPage:pageIndex+1 isNewPage:newPage];
	} else {
		[self removeAll:pageR];
	}
	curPage = page;
	page = [host genPage:pageIndex isNewPage:newPage];
	//NSLog(@"UIPageScrollView getPage %@ %i %i", host, pageIndex, newPage);
}


- (void)checkPageNeedMove {
	if (isHorizontalScroll) {
		if (self.contentOffset.x < -pageGap && pageNo > 0) {
			[self movePage:-1];
		} else if ((self.contentOffset.x-pageOriginalWidth*(self.zoomScale-self.minimumZoomScale)) > pageGap && pageNo < pageQuantity-1) {
			[self movePage:1];
		}		
	} else {
		if (self.contentOffset.y < -pageGap && pageNo > 0) {
			[self movePage:-1];
		} else if ((self.contentOffset.y-pageOriginalHeight*(self.zoomScale-self.minimumZoomScale)) > pageGap && pageNo < pageQuantity-1) {
			[self movePage:1];
		}
	}
}

- (PageView*)genPage:(NSInteger)pageIndex isNewPage:(BOOL)newPage {
	PageView *_page;
	if (!newPage) {
		[self removeAll:curPage];
		//[curPage release];
		_page = curPage;
	} else {
		_page = [[PageView alloc] initWithFrame:CGRectMake(0,0,frameWidth,frameHeight)];
	}
	return _page;
}

- (void)jumpPage:(int)_pageNo{
	pageNo = _pageNo;
	//NSLog(@"UIPageScrollView jumpPage %i %i", _pageNo, pageQuantity);
	[self getPage:pageNo isNewPage:FALSE];

	[self setContentOffset:CGPointMake(0, 0)];
	[self setZoomScale:self.minimumZoomScale];
	page.userInteractionEnabled = self.userInteractionEnabled = TRUE;
	page.multipleTouchEnabled = self.multipleTouchEnabled = TRUE;
	self.alwaysBounceHorizontal = YES;
	self.scrollEnabled = YES;
	self.bounces = YES;
	isPageMoving = NO;

	[host jumpPageDid:pageNo+1 pageQuantity:pageQuantity];
	//NSLog(@"UIPageScrollView jumpPage %i, contentSize:%f %f", [self.subviews count], self.contentSize.width, self.contentSize.height);
}

- (void)movePage:(int)dir {
	if (isPageMoving || (pageNo<=0 && dir <0) || (pageNo>=pageQuantity-1 && dir >0)) {
		return;
	}
	isPageMoving = YES;
	lastContentOffset = self.contentOffset;
	//NSLog(@"movePage %f", self.contentOffset.x);
	page.userInteractionEnabled = self.userInteractionEnabled = FALSE;
	page.multipleTouchEnabled = self.multipleTouchEnabled = FALSE;
	self.alwaysBounceHorizontal = NO;
	self.scrollEnabled = NO;
	self.bounces = NO;
	pageNo += 1*dir;
	int posx;
	int posy;
	if (isHorizontalScroll) {
		posy = self.contentOffset.y;
		int pw = pageOriginalWidth*(self.zoomScale-self.minimumZoomScale);
		if (dir > 0) {
			posx = pw+pageWidth+pageGap;
		} else {
			posx = -pageWidth-pageGap;
		}
	} else {
		posx = self.contentOffset.x;
		int ph = pageOriginalHeight*(self.zoomScale-self.minimumZoomScale);
		if (dir > 0) {
			posy = ph+pageHeight+pageGap;
		} else {
			posy = -pageHeight-pageGap;
		}		
	}
	[self setContentOffset:lastContentOffset animated:NO];
	[self setContentOffset:CGPointMake(posx, posy) animated:YES];		
	
}

- (void)removeAll:(PageView *)_page {
	if (_page == nil) {
		_page = curPage;
	}
	for (UIView *view in _page.subviews) {
		for (UIView *view2 in view.subviews) {
			[view2 removeFromSuperview];
		}
		[view removeFromSuperview];
	}	
}

#pragma mark -
#pragma mark UIScrollView Event

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
	if (isPageMoving) {
		[self jumpPage:pageNo];
	}
}

/*- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
 [self checkPageNeedMove];
 }*/

-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
	if (isPageMoving) {
		//NSLog(@"scrollViewWillBeginDecelerating");
		[scrollView setContentOffset:lastContentOffset animated:NO];
	}
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
	//NSLog(@"scrollViewDidEndDragging %i", decelerate);
	[self checkPageNeedMove];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
	if (isHorizontalScroll) {
		int posy = scrollView.contentOffset.y;
		pageL.center = CGPointMake(pageL.center.x, pageHeight2+posy);
		pageR.center = CGPointMake(pageOriginalWidth*scrollView.zoomScale+pageWidth2+pageGap, pageHeight2+posy);		
	} else {
		int posx = scrollView.contentOffset.x;
		pageL.center = CGPointMake(pageWidth2+posx, page.center.y-pageOriginalHeight*scrollView.zoomScale/2-pageHeight2-pageGap);
		pageR.center = CGPointMake(pageWidth2+posx, pageOriginalHeight*scrollView.zoomScale+pageHeight2+pageGap);		
	}
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
	return curPage;
}

# pragma mark -
# pragma mark Mouse Event

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
	NSLog(@"UIPageScrollView touchesBegan");
	[[NSNotificationCenter defaultCenter] postNotificationName:@"PageTouchesBegan" object:self];
}

- (void)doubleTapZoom:(NSNotification *)notification {
	//NSLog(@"doubleTapZoom");
	[self _doubleTapZoom];
}

- (void)_doubleTapZoom {
	if (self.zoomScale < self.maximumZoomScale) {
		[self setZoomScale:self.maximumZoomScale animated:YES];
	} else {
		[self setZoomScale:self.minimumZoomScale animated:YES];
	}
}

# pragma mark -

- (void)dealloc {
	NSLog(@"UIPageScrollView dealloc");
	[curPage release];
	[pageL release];
	[pageR release];
	[page release];
    [super dealloc];
}

@end
